<script>

import Cell from './YmCell'
import { COLUMNS, EMBEDDED, ROWS, SELECTABLE } from "@/store/table";

/**
 * @typedef {{}} Action :{ ...el-button }
 */
/**
 * @typedef {{}} Selector :{ ...el-table-column }
 */
/**
 * @typedef {{}} Column :{ name: el-table-column-prop,  ...el-table-column }
 */

/**
 * 构建 el-table
 *    {
 *      columns: array<Column>,
 *      selectable: Selector|false
 *      actions: array<Action>
 *    }
 */
export default {
  functional: true,
  render (h, context) {
    const { props, data, listeners } = context
    // 构建列
    let columns = []
    if (props[COLUMNS]) {
      columns = props[COLUMNS].map((column) => {
        return h('el-table-column', {
          props: {
            prop: column.name,
            ...column
          },
          scopedSlots: {
            default: ({ row }) => {
              return Cell(h, column, row)
            }
          }
        })
      })
    }
    // 选择列
    if (props[SELECTABLE] !== false) {
      columns.unshift(h('el-table-column', {
        props: {
          type: 'selection',
          headerAlign: 'center',
          align: 'center',
          width: '55',
          ...props[SELECTABLE]
        }
      }))
    }
    // 行操作
    if (props[EMBEDDED] && props[EMBEDDED].items) {
      const embedded = props[EMBEDDED]
      const items = embedded.items
      let click = listeners && listeners.click
      const width = (items.length * 80 + 20) + 'px'
      columns.push(h('el-table-column', {
        props: {
          label: '操作',
          width,
          align: 'center',
          ...embedded
        },
        scopedSlots: {
          default: scope => items.map((action) => {
            let data = {
              props: {
                type: 'text',
                size: 'mini',
                ...action,
                row: scope.row
              }
            }
            if (click) {
              data.on = {
                click: () => { click(action, scope.row) }
              }
            }
            return h('Ym-button', data, action.label)
          })
        }
      }))
    }

    return h(
      'el-table',
      {
        style: {
          width: '100%'
        },
        ...data,
        props: {
          ...data.props,
          data: props[ROWS],
          border: true
        },
        on: listeners
      },
      columns
    )
  }
}

</script>
